package com.black.play.component.base;

import lombok.Getter;
import lombok.Setter;

import javax.swing.*;
import java.io.File;
import java.util.function.Consumer;

/**
 * @author ylx
 */
@Getter
@Setter
public class AppFileChooser extends JFileChooser {

    public AppFileChooser(int mode, String defaultPath) {
        setFileSelectionMode(mode);
        setCurrentDirectory(new File(defaultPath));
    }

    /**
     * 打开文件选择器
     *
     * @param onSelect 选择文件后触发的回调, 与JFileChooser原生的不同
     */
    public void open(Consumer<File> onSelect) {
        int result = showOpenDialog(null);
        File selectedFile = this.getSelectedFile();
        if (result == JFileChooser.APPROVE_OPTION && selectedFile != null) {
            onSelect.accept(selectedFile);
        }
    }

    public static AppFileChooser singleFileChooser(String defaultPath) {
        return new AppFileChooser(JFileChooser.FILES_ONLY, defaultPath);
    }

    public static AppFileChooser singleFolderChooser(String defaultPath) {
        return new AppFileChooser(JFileChooser.DIRECTORIES_ONLY, defaultPath);
    }

    public static AppFileChooser multiFileChooser(String defaultPath) {
        return new AppFileChooser(JFileChooser.FILES_AND_DIRECTORIES, defaultPath);
    }
}
